package com.own.component.common.handler;

import com.own.component.common.em.RequestEnum;
import com.own.component.common.exception.BusinessException;
import com.own.component.common.exception.BusinessSimpleException;
import com.own.component.common.model.ExceptionMessageModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * BusinessExceptionHandler
 *
 * @author chenxueli
 * @date 2020/11/5 9:34
 */
@Slf4j
@Order(99)
@RestControllerAdvice
public class BusinessExceptionHandler {

    // todo 使用code针对不同的异常返回提示信息修改

    @ExceptionHandler(BusinessSimpleException.class)
    public ExceptionMessageModel handleBusinessSimpleException(BusinessSimpleException e) {
        log.error(e.getMessage());
        return new ExceptionMessageModel(e);
    }

    @ExceptionHandler(NullPointerException.class)
    public ExceptionMessageModel handleNullPointerException(NullPointerException e) {
        log.error(e.getMessage(), e);
        return new ExceptionMessageModel(RequestEnum.NULL_POINTER);
    }

    @ExceptionHandler(RuntimeException.class)
    public ExceptionMessageModel handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return new ExceptionMessageModel(e);
    }

    @ExceptionHandler(SQLException.class)
    public ExceptionMessageModel handleSqlException(SQLException e) {
        log.error(e.getMessage(), e);
        return new ExceptionMessageModel(RequestEnum.SQL_ERROR);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ExceptionMessageModel handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return new ExceptionMessageModel(RequestEnum.DUPLICATE_KEY);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ExceptionMessageModel handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return new ExceptionMessageModel(RequestEnum.PARAMETER_NOT_MATCH);
    }

    @ExceptionHandler(BusinessException.class)
    public ExceptionMessageModel handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return new ExceptionMessageModel(e);
    }

}
